const path = require('path');
const isDev = think.env === 'development';

module.exports = [
  {
    handle: 'meta',
    options: {
      logRequest: isDev,
      sendResponseTime: isDev
    }
  },
  {
    handle: 'resource',
    enable: isDev,
    options: {
      root: path.join(think.ROOT_PATH, 'www'),
      publicPath: /^\/(static|favicon\.ico)/
    }
  },
  {
    handle: 'trace',
    enable: !think.isCli,
    options: {
      debug: isDev
    },
    error(err, ctx) {
      ctx.respond = false;
      // 这里可以根据需要对错误信息进行处理，如：上报到监控系统
      let errmsg;
      if (err.isCustom) { // 自定义异常
        errmsg = err.message;
      } else {
        think.logger.error('系统错误:ERROR:', err.message);
        errmsg = '系统忙，请稍后重试';
      }
      ctx.res.writeHead(200, {'content-type': 'application/json; charset=utf-8'});
      if (typeof err.errno === 'string') {
        err.errno = 1000;
      }
      ctx.res.write(JSON.stringify({
        errno: err.errno || 1000,
        errmsg,
        data: ''
      }));
      ctx.res.end();
    }
  },
  {
    handle: 'payload',
    options: {
      keepExtensions: true,
      limit: '5mb'
    }
  },
  {
    handle: 'router',
    options: {}
  },
  'logic',
  'controller'
];
